<?php
/**
*  会员班级课程
*/
namespace app\api\model;
use think\Model;

class MemberClass extends Model
{
    /**
    *  列表
    */
    public function _list($where = '', $order_by="mc.created desc", $page_size = PAGE_SIZE_API){
        $obj = $this->order($order_by);
        $data = $this->alias('mc')->where($where)
            ->field('mc.*, cc.title, cc.image, cc.id as class_id, cc.instruce')
            ->join("class_course cc", 'cc.id=mc.cid', 'LEFT')
            ->order($order_by)
            ->paginate($page_size)
            ->toArray();
        return $data;
    }
    
    
    /**
    * 通过id获取信息
    */
    public function _getInfoByID($id){
        return $this->where([['id', '=',$id]])->find();
    }
    
    
    /**
    * 通过条件获取信息
    */
    public function _getInfoByWhere($where){
        return $this->where($where)->find();
    }
    
    /**
    * 签署协议
    * @param mid int 会员id
    * @param id int 协议id
    */
    public function _signAgreement($mid, $id){
        
        
        $this->startTrans();
        
        
        $where = ['mid'=>$mid, 'agree_id'=>$id];
        $data = $this->_getInfoByWhere($where);
        
        if(empty($data)){
            $this->error = '协议不存在';
            return false;
        }
        
        $model = new MemberCourseAgreement;
        $ret = $model->_signAgreement($mid, $id);
        if(!$ret){
            $this->error = $model->getError();
            return false;
        }
        
        if($data['is_sign_agreement'] == 1){
            $this->error = '协议已签署';
            return false;
        }
        
        $ret = $this->where(['mid'=>$mid, 'agree_id'=>$id, 'is_sign_agreement'=>-1])->update(['is_sign_agreement'=>1, 'sign_time'=>time()]);
        if(!$ret){
            $this->error = '协议签署失败';
            return false;
        }
        $this->commit();
        return true;
    }
    
    /**
    * 获取该班级的所有课程
    */
    public function _getAllCourse($post){
        if(empty($post['id'])){
            $this->error = '班级id缺失';
            return false;
        }
        
        $class_id = (int)$post['id'];
        $mid = (int)$post['mid'];
        $model = new ClassPlan;
        $list = $model->_getList($mid, $class_id);
        return $list;
    }

    /**
    * 更新进度
    */
    public function _updateProgress($id, $progress){
        return $this->where(['id'=>$id])->update(['progress'=>$progress]);
    }

}